package com.atues.thread.lock;

import java.util.concurrent.locks.ReentrantLock;

public class TestReentranLock {
    public static void main(String[] args) {
        // 创建一个买票的线程
        BuyTicket buyTicket = new BuyTicket();
        Thread thread1 = new Thread(buyTicket, "小明");
        Thread thread2 = new Thread(buyTicket, "小蓝");
        Thread thread3 = new Thread(buyTicket, "小红");

        // 启动线程
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class BuyTicket implements Runnable {
    private int ticket = 10;
    private final ReentrantLock lock = new ReentrantLock();
    private boolean flag = true; // true表示正在售票，false表示停止售票
    @Override
    public void run() {
        while (flag) {
            buy();
        }
    }

    //对方法进行上锁；锁==队列排队+阻塞，如果进入了同步代码，那么其他线程就不能进入了
    private  void buy() {
        // 锁的粒度是方法级别的
        lock.lock();
        if (ticket <= 0) {
            flag = false;
            return;
        }
        // 模拟网络延迟
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(Thread.currentThread().getName() + "买票，票号：" + ticket);
        ticket--;
        lock.unlock();
    }
}
